#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: set fileencoding=utf-8

import sys, os, getopt, re
import codecs
#from pysqlite2 import dbapi2 as sqlite
import sqlite3
from index_gen import *
from SCTC import *


DEFAULT_DIR = 'dragon_pedia/'
TRADITIONAL_DIR = 'dragon_pedia_t/'
DEFAULT_PRIFIX = 'dracondict_'
TRADITIONAL_PRIFIX = 'dracondict_t_'


def genWordBody(fout, row):
    if row['accuracy'] != 0:
        data = re.sub(r'<img(\s*\S*?\s*)src="([\w-]*\.\w*)"(\s*\S*?\s*)[/]??>', r'{{:dragon_pedia:\2?|}}', row['data'])
    else:
        data = u"""本词条还没有翻译。您可以使用以下工具搜索英文版资料：

[[http://www.sitelevel.com/query_v2.go?crid=496f32e1147dd5a2&amp;query=%s&amp;slice_title=&amp;page=1|在theserenedragon.net上搜索]]

[[http://www.google.com/search?hl=en&amp;q=%s|使用google搜索]]

[[http://dracopedia.wikispaces.com/search/view/%s|在dracopedia上搜索]]

[[http://www.google.com/cse?cx=008725003508402829375%%3Afsydnxovpzu&amp;ie=UTF-8&amp;q=%s&amp;sa=Search|在The Circle of the Dragon上搜索]]

""" % (row['title'], row['title'], row['title'], row['title'])

    data = re.sub(r'\r', r'', data)
    data = re.sub(r'\n', r'', data)
    data = re.sub(r'<p>', r'', data)
    data = re.sub(r'&nbsp;', r'', data)
    data = re.sub(r' ', r'', data)
    data = re.sub(r'</p>', r'\n\n', data)
    data = re.sub(r'<b>', r'**', data)
    data = re.sub(r'</b>', r'**', data)

    div = u"""
====== %s ======
所属文化：%s
    """ % (row['title'], row['culture'])

    div += u"""

%s
    """ % data

    fout.write(div)


class STConvert():
    def __init__(self, out):
        self.out = out

    def write(self, string):
        self.out.write(tc_to_sc(string))

def generator(dbfile, traditional=False):
    print 'input db file:', dbfile
    con = sqlite3.connect(dbfile)
    con.row_factory = sqlite3.Row
    cur = con.cursor()

    os.mkdir(DEFAULT_DIR)

    #multi_head(outer_index)

    #outer_index.write(u'<div class="h2"><h2>索引</h2>')
    #outer_index.write(u'<div class="list">')

    cur.execute('select * from pedia order by accuracy desc, id')
    for row in cur:
        if row['accuracy'] == 0:
            continue
        filename = DEFAULT_DIR + row['id'] + '.txt'
        filename = filename.lower()
        filename = re.sub(r'-', r'_', filename)
        f_word = codecs.open(filename, 'w', 'utf8')
        outer_word = f_word
        if not traditional:
            outer_word = STConvert(f_word)
        #genWordHead(outer_word, row)
        genWordBody(outer_word, row)
        #genWordTail(outer_word, row)
        f_word.close()

    #outer_index.write(u'</div></div>')
    #public_tail(outer_index)

    cur.close()

def usage():
    print("""
    example: xxx.py -i xx.db -o xx.html

    -h   print this message
    -i   input database name
    """)

def main(argv):
    global DEFAULT_DIR
    global DEFAULT_PRIFIX
    file_db = 'dpedia.db.sqlite'
    traditional = False
    try:
        opts, args = getopt.getopt(argv, 'hi:t', ['help', 'input=', 'traditional']) 
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage()
            sys.exit()
        elif opt in ('-i', '--input'):
            file_db = arg
        elif opt in ('-t', '--traditional'):
            traditional = True
    if traditional:
        DEFAULT_DIR = TRADITIONAL_DIR 
        DEFAULT_PRIFIX = TRADITIONAL_PRIFIX
    generator(file_db, traditional)

if __name__ == '__main__':
    main(sys.argv[1:])
